package com.jbh.fourclibrary.util;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;

public class Util {



    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        if (Build.VERSION.SDK_INT>=19) {
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = context.getResources().getDimensionPixelSize(resourceId);
            }
            return result;
        }
        return result;
    }



    /**
     *  设置着色图片
     * @param resourceId 图片资源id
     * @param color 颜色资源 id
     * @return 图片
     */
    public static Drawable GetTintDrawable(Context context,int resourceId, int color) {
        Drawable originalDrawable = ContextCompat.getDrawable(context, resourceId);
        assert originalDrawable != null;
        Drawable tintDrawable = DrawableCompat.wrap(originalDrawable).mutate();
        DrawableCompat.setTintList(tintDrawable, ContextCompat.getColorStateList(context, color));
        return tintDrawable;
    }



    /***
     * 屏幕的宽度
     */
    public static int  getWidth(Context context){
        return  context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 屏幕的高度
     * @return
     */
    public static int getHeight(Context context){
        return context.getResources().getDisplayMetrics().heightPixels;
    }



    public static int dpToPx(Resources res, int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, res.getDisplayMetrics());
    }

    public static int dpToPx(Context context,int dp) {
        float density=context.getResources().getDisplayMetrics().density;
        return (int) (density * dp  + 0.5f);
    }

    /**
     * 得到AppCompactActivity
     *
     * @param context 上下文
     * @return
     */
    public static AppCompatActivity getAppCompatActivity(Context context) {
        if (context == null) {
            return null;
        }
        if (context instanceof AppCompatActivity) {
            return (AppCompatActivity) context;
        } else if (context instanceof ContextThemeWrapper) {
            return getAppCompatActivity(((ContextThemeWrapper) context).getBaseContext());
        }
        return null;
    }

}
